package xyz.lilei23.framework.bean;

import xyz.lilei23.framework.core.BeanFactory;
import xyz.lilei23.framework.utils.CollectionUtils;
import xyz.lilei23.framework.utils.StringUtils;

import java.beans.PropertyDescriptor;

/**
 * PropertyInstantiationAwareBeanPostProcessor
 * @author jack
 * @date 31/07/2021 16:20
 * @version 1.0
 **/
public class PropertyInstantiationAwareBeanPostProcessor implements InstantiationAwareBeanPostProcessor {

    /**
     * bean工厂
     */
    private BeanFactory beanFactory;


    public PropertyInstantiationAwareBeanPostProcessor(BeanFactory beanFactory) {
        this.beanFactory = beanFactory;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws RuntimeException {
        GenericBeanDefinition beanDefinition = (GenericBeanDefinition) beanFactory.getBeanDefinition(beanName);
        if (CollectionUtils.isEmpty(beanDefinition.getPropertiesArgs())){
            return bean;
        }
        beanDefinition.getPropertiesArgs().forEach(propertyArg -> {
            try {
                // 使用内省设置值
                PropertyDescriptor descriptor= new PropertyDescriptor(propertyArg.getName(), bean.getClass(),
                        "get"+ BeanFactory.capitalize(propertyArg.getName()), "set" + BeanFactory.capitalize(propertyArg.getName()));
                if (!StringUtils.isEmpty(propertyArg.getValue())) {
                    descriptor.getWriteMethod().invoke(bean, propertyArg.getValue());
                }else {
                    descriptor.getWriteMethod().invoke(bean, beanFactory.getBean(propertyArg.getName()));
                }
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("属性设值后置处理异常: " + beanName);
            }
        });
        return bean;
    }

}
